package com.trsj.lnsj.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class ExcelImportUtils {
  // @描述：是否是2003的excel，返回true是2003
  public static boolean isExcel2003(String filePath) {
    return filePath.matches("^.+\\.(?i)(xls)$");
  }

  // @描述：是否是2007的excel，返回true是2007
  public static boolean isExcel2007(String filePath) {
    return filePath.matches("^.+\\.(?i)(xlsx)$");
  }

  public static boolean checkExcel(Workbook uploadWk, String filePath) {
    File templateFile = new File(filePath);
    InputStream is = null;
    boolean flag = true;
    try {
      is = new FileInputStream(templateFile);
      Workbook mbWb = WorkbookFactory.create(is);
      Sheet mbSheet = mbWb.getSheetAt(0);
      Sheet upSheet = uploadWk.getSheetAt(0);
      Cell firstRowCellForMb = mbSheet.getRow(0).getCell(0);
      firstRowCellForMb.setCellType(Cell.CELL_TYPE_STRING);
      Cell firstRowCellForUp = upSheet.getRow(0).getCell(0);
      firstRowCellForUp.setCellType(Cell.CELL_TYPE_STRING);
      // 比较模板第一行是否相同
      int totalCells = mbSheet.getRow(0).getPhysicalNumberOfCells();
      for (int i = 0; i < totalCells; i++) {
        Cell cellMb = mbSheet.getRow(0).getCell(i);
        cellMb.setCellType(Cell.CELL_TYPE_STRING);
        Cell cellUp = upSheet.getRow(0).getCell(i);
        cellUp.setCellType(Cell.CELL_TYPE_STRING);
        if (!cellMb.getStringCellValue().trim().equals(cellUp.getStringCellValue().trim())) {
          flag = false;
          break;
        }
      }

    } catch (Exception e) {
      flag = false;
      e.printStackTrace();
    } finally {
      if (is != null) {
        try {
          is.close();
        } catch (IOException e) {
          is = null;
          e.printStackTrace();
        }
      }
    }
    return flag;
  }

  /**
   * 验证EXCEL文件
   * 
   * @param filePath
   * @return
   */
  public static boolean validateExcel(String filePath) {
    if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
      return false;
    }
    return true;
  }
}
